package org.lewis.man.controllers;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lewis.common.service.SongService;
import org.lewis.common.utils.WebUtils;

import com.tocersoft.framework.core.annotations.Controller;
import com.tocersoft.framework.core.annotations.Injection;
import com.tocersoft.framework.core.cache.OSCacheManager;
import com.tocersoft.framework.web.annotations.Mapping;
import com.tocersoft.framework.web.annotations.NameSpace;
import com.tocersoft.framework.web.renderer.Renderer;

/**
 * 歌曲
 * 
 * @author taiqichao
 * 
 */
@Controller
@NameSpace("/song")
public class SongController {

	Log log = LogFactory.getLog(SongController.class);

	OSCacheManager cacheMang = OSCacheManager.getInstance();

	/** 收听次数ip缓存时间* */
	public static final int ipcachetimer = 1 * 60;

	public static final String ipcachekey = "songListeningIpMap";

	@Injection
	SongService songService;

	/**
	 * 更新歌曲收听次数
	 * 
	 * @return
	 * @throws Exception
	 */
	@Mapping("/updatelistening/$1")
	@SuppressWarnings("unchecked")
	public Renderer updateListening(long songId) throws Exception {

		String ip = WebUtils.getIpAddr();

		Map<String, Date> map = (Map<String, Date>) cacheMang.getCache(
				ipcachekey, ipcachetimer);

		if (map == null) {
			map = new HashMap<String, Date>();
			refresh(songId, ip, map);
		} else {
			if (map.get(ip+"_"+songId) == null) {
				refresh(songId, ip, map);
			}
		}

		return null;
	}

	private void refresh(long songId, String ip, Map<String, Date> map) {
		map.put(ip+"_"+songId, new Date());
		cacheMang.putCache(ipcachekey, map);
		songService.updateSongListening(songId);
	}

}
